package dp;

/**
 * 最优路径和
 * 举例：
 * 输入:
 * arr = [
 *   [1,3,1],
 *   [1,5,1],
 *   [4,2,1]
 * ]
 * 输出: 7
 * 解释: 因为路径 1→3→1→1→1 的总和最小。
 */
public class OptimalPathSum {

    public static void main(String[] args) {
        int[][] map = new int[][] {
                {1,3,1},
                {1,5,1},
                {4,2,1}
        };
        int sum = getOptimalPathSum(map);
        System.out.println("最小路径和是"+sum);
    }

    public static int getOptimalPathSum(int[][] map) {
        int m = map.length;
        int n = map[0].length;
        int[][] dp = new int[m][n];
        dp[0][0] = map[0][0];
        for (int i = 1; i < n; i++) {
            dp[0][i] = dp[0][i-1] + map[0][i];
        }
        for (int j = 1; j < n; j++) {
            dp[j][0] = dp[j-1][0] + map[j][0];
        }
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                dp[i][j] = Math.min(dp[i-1][j], dp[i][j-1]) + map[i][j];
            }
        }
        Common.print2dArr(dp);
        return dp[m-1][n-1];
    }
}
